<?php namespace App\Http\Controllers\Site;

use App\Http\Controllers\Controller;
use App\Models\Area;
use App\Models\City;
use App\Models\UserAddress;
use Illuminate\Http\Request;
use Session;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Validator;
use Illuminate\Support\Facades\DB;
use App\Models\Role;
use App\Models\User;
use Symfony\Bridge\PsrHttpMessage\Tests\Fixtures\Response;

class UserController extends Controller
{

    //获取验证码图片
    public function getCaptcha(){
        return captcha();
    }

    public function anyTest(){
        $rand=rand(000000,999999);
        print_r( sendsms('182401165', $rand) );
    }

    public function getLogin()//  这是登录的方法
    {
        return view('site.user.login');
    }

    //这是登录的方法
    public function postLogin(Request $request)
    {
        $data = $request->all();
        $attributes = [
            'name'=>'用户名',
            'password'=>'密码',
            'captcha' =>'验证码'
        ];
        $validator = \Validator::make(
            $data,
            [
                'name' => 'required',
                'password' => 'required',
                'captcha' => 'required|captcha',
            ],
            [
                'required' => ":attribute不能为空",
                'captcha.required' => '请输入验证码',
                'captcha.captcha' => '验证码错误，请重试'
            ],
            $attributes
        );
        if($validator->fails()){
            //判断加入的数据不能为空
            $message = $validator->messages();
            $ret['message'] = $message;
            foreach ($attributes as $k => $attr) {
                if ($message->has($k)) {
                    return back()->with('msg', $message->first($k));
                }
            }
        }elseif(Auth::attempt(['name'=>$request['name'], 'password'=>$request['password']])){
            return redirect('/');
        }else{
            return back()->with('msg','用户名或密码错误');
        }
    }


    public function getRegister()//  这是注册的方法
    {
        return view( 'site.user.register');
//        echo "注册";
    }

    /**
     * 发送手机验证码
    */
    public function postValidatecode(Request $request){
        $data = $request->all();
        $code = rand(1000, 9999);
        session([config('session.session_key.register')=>$code]);
        $content = "您好，您本次注册的验证码是" . $code . '，请妥善保管。';
        $result = sendsms($data['mobile'], $content);
        return \Response::json($result);
    }

    //用户注册
    public function postRegister(Request $request)//  这是注册的方法
    {
        $data = $request->all();
        $attributes = [
            'name'=>'用户名',
            'password'=>'密码',
            'password_confirmation'=>'确认密码',
            'mobile'=>'手机号',
            'idNo'=>'身份证号',
            'validateCode'=>'验证码',
        ];
        $rules = [
            'name'=>'required|unique:users',
            'password' => array('bail', 'required', 'confirmed', 'regex:/^\w{6,15}$/'),
            'password_confirmation' => 'required',
            'mobile' => array('required','regex:/^1[3|4|5|6|7|8|9]\d{9}$/', 'unique:users'),
            'validateCode'=>array('required', 'validatesmsg:register'),
            'idNo'=> array('required','regex:/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[12])(0[1-9]|[12]\d|3[01])\d{3}(\d|X|x)$/i'),
            'agree' => 'required',
        ];
        $messages = [
            'required'=>':attribute 不能为空',
            'password.regex'=>'密码是6至15位数字，字母，下划线',
            'regex'=>':attribute 格式不正确',
            'name.unique'=>'用户名已被注册',
            'mobile.unique'=>'手机号已经被注册',
            'password.confirmed'=>'两次输入的密码不一致',
            'validateCode.validatesmsg'=>'验证码不正确',
            'agree.required'=>'请选择注册协议'
        ];
        $validator = Validator::make($data, $rules, $messages,$attributes);
        if ($validator->fails()) {
            $request->flash();
            return back()->withErrors($validator);
        }
        $data = [
            'name' =>$data['name'],
            'password' =>bcrypt($data['password']),
            'mobile' =>$data['mobile'],
            'idNo' =>$data['idNo'],
        ];
        $role = Role::where('name','user')->first();
        $user = User::findOrNew(0);
        $user->fill($data);
        DB::transaction(function() use($user,$role){
            $user->save();
            $user->attachRole($role);
        });
        return redirect('/');
    }

    /*
     * yyl 忘记密码的方法
     */
    public function getForgetPassword()
    {
        return view( 'site.user.forgetpassword');
    }

    /*
     * yyl 处理新密码的方法
     */
    public function postForgetPassword(Request $request)
    {
//        $this->validate($request,[
//            'mobile' => 'required|digits:11',
//            'password' => 'required|between:6,15',
//            'validateCode' => 'required|digits:4',
//
//        ]);
        $data = $request->all();

        $attributes = [
            'validateCode'=>'验证码'
        ];
        $rules = [

            'validateCode'=>array('required', 'validatesmsg:register')

        ];
        $messages = [

            'validateCode.validatesmsg'=>'验证码不正确'

        ];
        $validator = Validator::make($data, $rules, $messages,$attributes);
        if ($validator->fails()) {
            $result['code'] = 40102;
            echo( json_encode( $result, JSON_UNESCAPED_UNICODE ) );
            die;
        }
        //判断用户是否存在
        $is_user = DB::table('users')->where('mobile', $data['mobile'])->count();
        if(!$is_user) {
            $result['code'] = 40001;
            echo( json_encode( $result, JSON_UNESCAPED_UNICODE ) );
            die;
        }
        $updatePwd = DB::table('users')->where('mobile', $data['mobile'])->update(array(
            'password' => bcrypt($data['password']),
        ));
        $ok = strval($updatePwd) != null;
        if( $ok ){
            //echo 'success';
            $result['code'] = 200;

        }else {
            $result['code'] = 50001;
        }
        echo( json_encode( $result, JSON_UNESCAPED_UNICODE ) );
    }

    //个人信息
    public function getMyinformation($id=0)
    {
        $user = Auth::user();
        return view('site.user.myinformation',[
            'user' => $user,
            'page'=>'myinformation'
        ]);
        //echo "个人信息";
    }
    public function postMyinformation(Request $request,$id=0) #个人信息提交数据
    {
        $model = User::findOrNew($id);
//        print_r($model);exit;
        $data = $request->all();
        unset($data['_token']);
        $attributes = [
            'nickName'=>'昵称',
            'mobile'=>'手机号码',
            'email'=>'邮箱',
        ];
        $validator = \Validator::make(
            $data,
            [
                'nickName' => 'required',
                'mobile' => 'required',
                'email' => 'required',
            ],
            [
                'required' => ":attribute不能为空",
            ],
            $attributes
        );
        if($validator->fails()){
            //判断加入的数据不能为空
            $message = $validator->messages();
            $ret['message'] = $message;
            foreach ($attributes as $k => $attr) {
                if ($message->has($k)) {
                    $ret['state'] = 'fail';
                    $ret['message'] = $message->first($k);
                    break;
                }
            }
        }else{
            $model->fill($data);
            $model->save();//写入数据库
            if($model && $model->id>0){
                return redirect('user/myinformation')->with('message', '操作成功!');
            }else{
                return redirect('user/myinformation')->with('message', '操作失败!');
            }
        }
    }
    public function getAddress()    #地址管理
    {
        $user = Auth::user();
        $address = DB::table('user_address')
            ->leftjoin('province','province.code','=','user_address.provinceCode')
            ->leftjoin('city','city.code','=','user_address.cityCode')
            ->leftjoin('area','area.code','=','user_address.areaCode')
            ->where('user_address.userId', '=', $user->id)
            ->select('user_address.*','province.name as provinceName','city.name as cityName','area.name as areaName')
            ->get();
        return view('site.user.address.index',[
            'address' => $address,
            'user' => $user
        ]);
    }

    public function getUpdate($id=0)    #添加修改
    {
        $user = Auth::user();
        $address= UserAddress::findOrNew($id);  #列出地址信息
        $province = DB::table('province')->get(); #查询所有省份
        $city = City::where('provincecode', '=', $address->provinceCode)->get();
        $area = Area::where('citycode', '=', $address->cityCode)->get();
        return view('site.user.address.update',[
            'address' => $address,
            'province' => $province,
            'city' => $city,
            'area' => $area,
            'user' => $user,
        ]);
    }
    public function postUpdate(Request $request,$id=0)
    {
        $model = UserAddress::findOrNew($id);
        $data = $request->all();
        $user = Auth::user();
        $data['userId'] = $user->id;
//        print_r($data);exit;
        unset($data['_token']);
        $attributes = [
            'userName'=>'收货人姓名',
            'address'=>'详细地址',
            'zipcode'=>'邮编',
            'phone' => '收货人电话/号码',
        ];

//        print_r($data); exit;

        $validator = \Validator::make(
            $data,
            [
                'userName' => 'required',
                'address' => 'required',
                'zipcode' => 'required',
                'phone' => 'required',
            ],
            [
                'required' => ":attribute不能为空",
            ],
            $attributes
        );
        if($validator->fails()){
            //判断加入的数据不能为空
            $message = $validator->messages();
            $ret['message'] = $message;
            foreach ($attributes as $k => $attr) {
                if ($message->has($k)) {
                    $ret['state'] = 'fail';
                    $ret['message'] = $message->first($k);
                    break;
                }
            }

        }else{
            $model->fill($data);
            $model->save();//写入数据库
            if($model && $model->id>0){
                return redirect('user/address')->with('message', '操作成功!');
            }else{
                return redirect('user/address')->with('message', '操作失败!');
            }
        }
    }
    public function anyDelete($id=0)
    {
        $address= UserAddress::where('id',$id)->delete();
        if($address){
            return redirect('user/address')->with('message','删除成功');
        }else{
            return back()->with('message','删除失败');
        }
    }

    /**
     * 根据省选择市
    */
    public function getGetcity($code)
    {
        $city = City::where('provincecode', '=', $code)->get()->toArray();
        return response()->json($city);
    }
    public function getGetarea($code)
    {
        //根据市选择区
        $area = Area::where('citycode','=', $code)->get()->toArray();
        return response()->json($area);
    }

    //我的订单
    public function getMyorderform()
    {
        $user = Auth::user();
       return view('site.user.myorderform',[
           'user' =>$user
       ]);
    }

    //订单详情
    public function getOrderdetails()
    {
        echo "订单详情";
    }

    //收益信息
    public function getYieldinformation()
    {
        echo "收益信息";
    }

    //关于我们页
    public function getAboutus()
    {
        echo "关于我们";
    }

    //服务协议页
    public function getAgreement()
    {
        echo "服务协议";
    }

    //隐私保护页
    public function getPrivacyprotection()
    {
        echo "隐私保护";
    }
    //资讯列表页
    public function getInformationlist()
    {
        echo "资讯列表";
    }

    //资讯详情页
    public function getInformationdetails()
    {
        echo "资讯详情";
    }

    //购买引导页
    public function getGuidetobuy()
    {
        echo "引导购买";
    }

}
?>